<template>
  <div class="order-exception">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select v-model="searchForm.exceptionType" placeholder="请选择" clearable>
            <el-option label="支付异常" value="payment" />
            <el-option label="退款异常" value="refund" />
            <el-option label="服务异常" value="service" />
            <el-option label="系统异常" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleExport">导出数据</el-button>
      <el-button type="success" @click="handleBatchProcess" :disabled="!selectedRows.length">
        批量处理
      </el-button>
    </div>

    <!-- 异常订单列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="exceptionType" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.exceptionType)">
              {{ getExceptionTypeLabel(row.exceptionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="异常描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              link 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button 
              v-if="['pending', 'processing'].includes(row.status)"
              type="danger" 
              link 
              @click="handleClose(row)"
            >
              关闭
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      :title="processForm.id ? '处理异常' : '批量处理异常'"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="solution">
          <el-select v-model="processForm.solution" placeholder="请选择处理方式">
            <el-option label="退款处理" value="refund" />
            <el-option label="重新下单" value="reorder" />
            <el-option label="补偿处理" value="compensation" />
            <el-option label="其他处理" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理说明"
          />
        </el-form-item>
        <el-form-item 
          v-if="processForm.solution === 'refund'"
          label="退款金额"
          prop="refundAmount"
        >
          <el-input-number
            v-model="processForm.refundAmount"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item 
          v-if="processForm.solution === 'compensation'"
          label="补偿金额"
          prop="compensationAmount"
        >
          <el-input-number
            v-model="processForm.compensationAmount"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="异常订单详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detailData.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="异常类型">
          <el-tag :type="getExceptionTypeTag(detailData.exceptionType)">
            {{ getExceptionTypeLabel(detailData.exceptionType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTag(detailData.status)">
            {{ getStatusLabel(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getPriorityTag(detailData.priority)">
            {{ getPriorityLabel(detailData.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常描述" :span="2">
          {{ detailData.description }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 处理记录 -->
      <div class="process-records">
        <h3>处理记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="record in detailData.processRecords"
            :key="record.id"
            :type="getTimelineItemType(record.status)"
            :timestamp="record.createTime"
          >
            <h4>{{ record.operator }}</h4>
            <p>处理方式：{{ getSolutionLabel(record.solution) }}</p>
            <p>处理说明：{{ record.remark }}</p>
            <p v-if="record.refundAmount">退款金额：¥{{ record.refundAmount }}</p>
            <p v-if="record.compensationAmount">补偿金额：¥{{ record.compensationAmount }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMerchantOrderExceptionList,
  processMerchantOrderException,
  batchProcessMerchantOrderException,
  closeMerchantOrderException,
  exportMerchantOrderExceptionList
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  exceptionType: '',
  status: '',
  dateRange: []
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 处理表单
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  solution: '',
  remark: '',
  refundAmount: 0,
  compensationAmount: 0
})

// 详情数据
const detailDialogVisible = ref(false)
const detailData = ref({})

// 表单验证规则
const processRules = {
  solution: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  remark: [{ required: true, message: '请输入处理说明', trigger: 'blur' }],
  refundAmount: [
    { 
      required: true, 
      message: '请输入退款金额', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (processForm.solution === 'refund' && !value) {
          callback(new Error('请输入退款金额'))
        } else {
          callback()
        }
      }
    }
  ],
  compensationAmount: [
    {
      required: true,
      message: '请输入补偿金额',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (processForm.solution === 'compensation' && !value) {
          callback(new Error('请输入补偿金额'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 获取异常类型标签
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    payment: '支付异常',
    refund: '退款异常',
    service: '服务异常',
    system: '系统异常'
  }
  return typeMap[type] || type
}

// 获取异常类型标签样式
const getExceptionTypeTag = (type) => {
  const typeMap = {
    payment: 'warning',
    refund: 'danger',
    service: 'info',
    system: 'error'
  }
  return typeMap[type] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已处理',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return statusMap[status] || ''
}

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

// 获取优先级标签样式
const getPriorityTag = (priority) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return priorityMap[priority] || ''
}

// 获取处理方式标签
const getSolutionLabel = (solution) => {
  const solutionMap = {
    refund: '退款处理',
    reorder: '重新下单',
    compensation: '补偿处理',
    other: '其他处理'
  }
  return solutionMap[solution] || solution
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return typeMap[status] || ''
}

// 获取异常订单列表
const getExceptionList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantOrderExceptionList(params)
    tableData.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取异常订单列表失败:', error)
    ElMessage.error('获取异常订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getExceptionList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 查看详情
const handleView = async (row) => {
  detailData.value = row
  detailDialogVisible.value = true
}

// 处理异常
const handleProcess = (row) => {
  processForm.id = row.id
  processForm.solution = ''
  processForm.remark = ''
  processForm.refundAmount = 0
  processForm.compensationAmount = 0
  processDialogVisible.value = true
}

// 批量处理
const handleBatchProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要处理的异常订单')
    return
  }
  processForm.id = ''
  processForm.solution = ''
  processForm.remark = ''
  processForm.refundAmount = 0
  processForm.compensationAmount = 0
  processDialogVisible.value = true
}

// 提交处理
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    if (processForm.id) {
      await processMerchantOrderException(processForm.id, processForm)
      ElMessage.success('处理成功')
    } else {
      const ids = selectedRows.value.map(row => row.id)
      await batchProcessMerchantOrderException(ids, processForm)
      ElMessage.success('批量处理成功')
    }
    processDialogVisible.value = false
    getExceptionList()
  } catch (error) {
    console.error('处理异常订单失败:', error)
  }
}

// 关闭异常
const handleClose = async (row) => {
  try {
    await ElMessageBox.confirm('确认关闭该异常订单吗？', '提示', {
      type: 'warning'
    })
    await closeMerchantOrderException(row.id)
    ElMessage.success('关闭成功')
    getExceptionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('关闭异常订单失败:', error)
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantOrderExceptionList(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getExceptionList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getExceptionList()
}

onMounted(() => {
  getExceptionList()
})
</script>

<style lang="scss" scoped>
.order-exception {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .process-records {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;

    h3 {
      margin-bottom: 20px;
      font-size: 16px;
      color: #303133;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 